﻿using LitJson;
using System.Collections.Generic;
using TableCore.Exceptions;

namespace TableCore.Plugin
{
    public class ArrayFormatter : IGenFormatter , IGenCmdInitializer
    {
        GTType mElementType;

        public IExportData ExportData(GTFile.Content content, string data, string cellName, string comment)
        {
            return null;
        }

        public JsonData Format(GTFile.Content content, string data, string cellName, string comment)
        {
            var dt = new JsonData(JsonType.Array);
            if (!string.IsNullOrEmpty(data))
            {
                var c0 = data[0];
                if (c0 == '[')
                    data = data.Substring(1, data.Length - 2);
                if (string.IsNullOrEmpty(data))
                    return dt;
                var arr = data.Split(',');
                for (int i = 0; i < arr.Length; i++)
                {
                    var str = arr[i].Trim();
                    if (mElementType != null)
                        str = mElementType.FormatInput(str);
                    if (mElementType != null && !mElementType.IsValid(str))
                        throw new ValueNotMatchTypeException(content, str, mElementType, cellName);
                    if (mElementType == null)
                        dt.Add(str);
                    else
                        dt.Add(mElementType.Format(content, str, cellName, comment));
                }
            }
            return dt;
        }

        public void Init(GTType type, Dictionary<string, string> args, string content)
        {
            string gttype;
            if (args.TryGetValue("item", out gttype) && !string.IsNullOrEmpty(gttype))
                mElementType = Factory.GetInstance().GetGenType(gttype);
            else if (args.TryGetValue("element", out gttype) && !string.IsNullOrEmpty(gttype))
                mElementType = Factory.GetInstance().GetGenType(gttype);
            else
                mElementType = null;
        }

        public bool IsValid(string data)
        {
            if (string.IsNullOrEmpty(data))
                return true;
            var c0 = data[0];
            if (c0 == '[')
                return data.Length > 1 && data[data.Length - 1] == ']';
            else
                return true;
        }
    }
}
